package org.example.day03;

/**
 * 第二章节2.1.2：实例变量非线程安全
 */
public class MyThread2{
    private int num = 0;
    public void addI(String username){
        try {
            if(username.equals("a")){
                num = 100;
                System.out.println("a set over");
                Thread.sleep(2000);
            }else {
                num = 200;
                System.out.println("b set over");
            }
            System.out.println(username + " num = " + num);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread2 m2 = new MyThread2();
        ThreadC tc = new ThreadC(m2);
        tc.start();
        ThreadD td = new ThreadD(m2);
        td.start();
    }
}

class ThreadC extends Thread{
    private MyThread2 m2;
    public ThreadC(MyThread2 m2){
        this.m2 = m2;
    }

    @Override
    public void run() {
        m2.addI("a");
    }
}

class ThreadD extends Thread{
    private MyThread2 m2;
    public ThreadD(MyThread2 m2){
        this.m2 = m2;
    }

    @Override
    public void run() {
        m2.addI("b");
    }
}

//线程C中的num发生脏读
//a set over
//b set over
//b num = 200
//a num = 200